<?php

/**
 * Author: Artem Azarov <bel-azar@ya.ru>
 * Date: 3/24/12
 * Time: 9:11 PM
 */

/**
 * model User
 *
 * @property integer $id
 * @property string $login
 * @property string $password
 * @property string $role
 */
class User extends CActiveRecord {
    const ROLE_ADMIN = 'administrator';
    const ROLE_USER = 'user';
    const SALT = 'kenny';

    public $rememberMe;

    public static function model($className=__CLASS__){
        return parent::model($className);
    }

    public function tableName(){
        return 'user';
    }
/*
    protected function beforeValidate(){
        $this->password = $this->encrypting($this->password);
        return parent::beforeValidate();
    }
*/
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('login, password', 'required'),
            array('rememberMe', 'boolean'),
            array('lastvisit', 'safe'),
            array('password', 'authenticate'),
        );
    }


    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
            'rememberMe' => Yii::t('main', "Remember Me Next Time"),
            'login'   => Yii::t('main', "Username Or Email"),
            'password'   => Yii::t('main', "Password"),
        );
    }


    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute, $params) {
        if(!$this->hasErrors()) {
            $identity = new UserIdentity($this->login, $this->password);
            $identity->authenticate();

            switch($identity->errorCode) {
                case UserIdentity::ERROR_NONE:
                    $duration = $this->rememberMe ? 3600*24*30 : 0; // 30 days
                    Yii::app()->user->login($identity, $duration);
                    break;
                case UserIdentity::ERROR_USERNAME_INVALID:
                    $this->addError("login",Yii::t('main', "Username/password is incorrect."));
                    break;
                case UserIdentity::ERROR_PASSWORD_INVALID:
                    $this->addError("password",Yii::t('main', "Username/password is incorrect."));
                    break;
                case UserIdentity::ERROR_EMAIL_INVALID:
                    $this->addError("login", Yii::t('main', "Email is incorrect."));
                    break;
            }
        }
    }

    /**
     * @return hash string.
     */
    public static function encrypting($string="") {
            return md5($string/*, self::SALT*/);
    }
}
